//
//  DataManager.m
//  DataManager
//
//  Created by Michael Hinds on 2/25/09.
//  Copyright 2009 University of Arkansas. All rights reserved.
//

#import "DataManager.h"


@implementation DataManager
@synthesize parser, remoteKey, userID, connection, data, imageView, caller;

/***************************CONSTRUCTOR********************************/
-(id) init
{
	return self;
}

-(id) initWithRemoteKey:(NSString *) rKey AndUserID:(NSString *) uID
{
	remoteKey = rKey;
	userID = uID;	
	
	return self;
}

/*****************************Getters & Setters************************/
//since the @property directives are used on the remote key and userID, then 
//we don't need getters and setters for them. They are automatically included.

/***************************API METHODS********************************/
//Get a user's Portfolio
-(NSDictionary *) getPortfolio
{
	
	//instantiate parser if not already done
	if(parser == NULL)
	{
		parser = [[SBJSON alloc] init]; 
	}
	
	//Debug
	NSLog(@"Entered getPortfolio method");
	
	NSString* fullURL = [NSString stringWithFormat:@"http://www.kaching.com/api/users/%@/portfolio", userID];
	
	NSLog(@"Created URL: %@", fullURL);
	
	// Prepare URL request to download Portfolio from KaChing
	NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:fullURL]];
	
	// Perform request and get JSON back as a NSData object
	NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
	
	// Get JSON as a NSString from NSData response
	NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
	//txtArea.text = [txtArea.text stringByAppendingString: json_string];
	
	NSLog(json_string);
	
	// parse the JSON response into an object
	NSDictionary *portfolio = [parser objectWithString:json_string error:nil];
	
	return portfolio;
	
	[json_string release];
}

//This method calls the Kaching API's get user watchlist method to retrieve an NSDictionary of the user's watchlist. 
-(NSDictionary *) getWatchlist
{
	
	//instantiate parser if not already done
	if(parser == NULL)
	{
		parser = [[SBJSON alloc] init]; 
	}
	
	//Debug
	NSLog(@"Entered getWatchlist method");
	
	NSString* fullURL = [NSString stringWithFormat:@"http://www.kaching.com/api/users/%@/watchlist", userID];
	
	NSLog(@"Created URL: %@", fullURL);
	
	// Prepare URL request to download Profile from KaChing
	NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:fullURL]];
	
	// Perform request and get JSON back as a NSData object
	NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
	
	// Get JSON as a NSString from NSData response
	NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
	//txtArea.text = [txtArea.text stringByAppendingString: json_string];
	
	NSLog(json_string);
	
	// parse the JSON response into an object
	NSDictionary *watchlist = [parser objectWithString:json_string error:nil];
	
	return watchlist;
	
	[json_string release];
}

//This method returns an NSDictionary of Pending orders
-(NSDictionary *) getPendingOrders
{
	//instantiate parser if not already done
	if(parser == NULL)
	{
		parser = [[SBJSON alloc] init]; 
	}
	
	//Debug
	NSLog(@"Entered getPendingOrders method");
	
	NSString* fullURL = [NSString stringWithFormat:@"http://www.kaching.com/api/users/%@/portfolio/orders", userID];
	
	NSLog(@"Created URL: %@", fullURL);
	
	// Prepare URL request to download Profile from KaChing
	NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:fullURL]];
	
	// Perform request and get JSON back as a NSData object
	NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
	
	// Get JSON as a NSString from NSData response
	NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
	//txtArea.text = [txtArea.text stringByAppendingString: json_string];
	
	NSLog(json_string);
	
	// parse the JSON response into an object
	NSDictionary *pendingOrders = [parser objectWithString:json_string error:nil];
	
	return pendingOrders;
	
	[json_string release];
}

//Gets user information including name, picture url, and userID
-(NSDictionary *) getUser
{
	
	//instantiate parser if not already done
	if(parser == NULL)
	{
		parser = [[SBJSON alloc] init]; 
	}
	
	//Debug
	NSLog(@"Entered getUser method");
	
	NSString* fullURL = [NSString stringWithFormat:@"http://www.kaching.com/api/users/%@", userID];
	
	NSLog(@"Created URL: %@", fullURL);
	
	// Prepare URL request to download user information from KaChing
	NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:fullURL]];
	
	// Perform request and get JSON back as a NSData object
	NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
	
	// Get JSON as a NSString from NSData response
	NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
	
	NSLog(json_string);
	
	// parse the JSON response into an object
	NSDictionary *user = [parser objectWithString:json_string error:nil];
	
	return user;
	
	[json_string release];
	
	//Debug
	NSLog(@"Exited getUser method!");
}

//Gets user's wall
-(NSDictionary *) getWall
{
	//instantiate parser if not already done
	if(parser == NULL)
	{
		parser = [[SBJSON alloc] init]; 
	}
	
	//Debug
	NSLog(@"Entered getWall method");
	
	NSString* fullURL = [NSString stringWithFormat:@"http://www.kaching.com/api/users/%@/wall", userID];
	
	NSLog(@"Created URL: %@", fullURL);
	
	// Prepare URL request to download user information from KaChing
	NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:fullURL]];
	
	// Perform request and get JSON back as a NSData object
	NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
	
	// Get JSON as a NSString from NSData response
	NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
	
	NSLog(json_string);
	
	// parse the JSON response into an object
	NSDictionary *wall = [parser objectWithString:json_string error:nil];
	
	return wall;
	
	[json_string release];
	
	//Debug
	NSLog(@"Exited getPerformance method!");
}

//Gets a wall for the specified stock
-(NSDictionary *) getWallForStock:(NSString *) ticker
{
	//instantiate parser if not already done
	if(parser == NULL)
	{
		parser = [[SBJSON alloc] init]; 
	}
	
	//Debug
	NSLog(@"Entered getWall method");
	
	NSString* fullURL = [NSString stringWithFormat:@"http://www.kaching.com/api/securities/%@/wall", ticker];
	
	NSLog(@"Created URL: %@", fullURL);
	
	// Prepare URL request to download user information from KaChing
	NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:fullURL]];
	
	// Perform request and get JSON back as a NSData object
	NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
	
	// Get JSON as a NSString from NSData response
	NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
	
	NSLog(json_string);
	
	// parse the JSON response into an object
	NSDictionary *wall = [parser objectWithString:json_string error:nil];
	
	return wall;
	
	[json_string release];
	
	//Debug
	NSLog(@"Exited getPerformance method!");
}

//Gets user performance data
-(NSDictionary *) getPerformance:(NSString *) from
{
	//instantiate parser if not already done
	if(parser == NULL)
	{
		parser = [[SBJSON alloc] init]; 
	}
	
	//Debug
	NSLog(@"Entered getPerformance method");
	
	NSString* fullURL = [NSString stringWithFormat:@"http://www.kaching.com/api/users/%@/portfolio/performance?from=%@", userID, from];
	
	NSLog(@"Created URL: %@", fullURL);
	
	// Prepare URL request to download user information from KaChing
	NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:fullURL]];
	
	// Perform request and get JSON back as a NSData object
	NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
	
	// Get JSON as a NSString from NSData response
	NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
	
	NSLog(json_string);
	
	// parse the JSON response into an object
	NSDictionary *performance = [parser objectWithString:json_string error:nil];
	
	return performance;
	
	[json_string release];
	
	//Debug
	NSLog(@"Exited getPerformance method!");
}


- (void)connectionDidFinishLoading:(NSURLConnection*)theConnection {
	
    [connection release];
    connection=nil;
}

//Gets a security
-(NSDictionary *) getSecurity:(NSString *) ticker
{
	//instantiate parser if not already done
	if(parser == NULL)
	{
		parser = [[SBJSON alloc] init]; 
	}
	
	//Debug
	NSLog(@"Entered getPerformance method");
	
	NSString* fullURL = [NSString stringWithFormat:@"http://www.kaching.com/api/securities/%@", ticker];
	
	NSLog(@"Created URL: %@", fullURL);
	
	// Prepare URL request to download user information from KaChing
	NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:fullURL]];
	
	//add the API key (J-BJc1KZEiTQdphsMCsW3DUbWsjgqTo5) as a header
	[request addValue:@"J-BJc1KZEiTQdphsMCsW3DUbWsjgqTo5" forHTTPHeaderField:@"X-KaChing-APIKey"];	
	
	// Perform request and get JSON back as a NSData object
	NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
	
	// Get JSON as a NSString from NSData response
	NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
	
	NSLog(json_string);
	
	// parse the JSON response into an object
	NSDictionary *security = [parser objectWithString:json_string error:nil];
	
	return security;
	
	[json_string release];
	
	//Debug
	NSLog(@"Exited getPerformance method!");
}

//This method puts the ticker string into the user's watchlist
-(void) addToWatchList:(NSString *) ticker
{
	//create a string to be used as the request's URL
	NSString* fullURL = [NSString stringWithFormat:@"http://www.kaching.com/api/users/%@/watchlist/%@", userID, ticker];
	
	// Prepare URL request with the above URL
	NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:fullURL]];
	
	//change the content length header to 0 since we are not sending or receiving any data in the body.
	[request addValue:@"0" forHTTPHeaderField:@"Content-Length"];
	
	//add the remote key as a header
	[request addValue:remoteKey forHTTPHeaderField:@"X-KaChing-RemoteKey"];
	
	//add the API key (J-BJc1KZEiTQdphsMCsW3DUbWsjgqTo5) as a header
	[request addValue:@"J-BJc1KZEiTQdphsMCsW3DUbWsjgqTo5" forHTTPHeaderField:@"X-KaChing-APIKey"];	
	
	//Set the request method to PUT
	[request setHTTPMethod:@"PUT"];
	
	// Perform request
	[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
}

//This method removes the ticker string from the user's watchlist
-(void) removeFromWatchList:(NSString *) ticker
{
	//create a string to be used as the request's URL
	NSString* fullURL = [NSString stringWithFormat:@"http://www.kaching.com/api/users/%@/watchlist/%@", userID, ticker];
	
	// Prepare URL request with the above URL
	NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:fullURL]];
	
	//change the content length header to 0 since we are not sending or receiving any data in the body.
	[request addValue:@"0" forHTTPHeaderField:@"Content-Length"];
	
	//add the remote key as a header
	[request addValue:remoteKey forHTTPHeaderField:@"X-KaChing-RemoteKey"];
	
	//add the API key (J-BJc1KZEiTQdphsMCsW3DUbWsjgqTo5) as a header
	[request addValue:@"J-BJc1KZEiTQdphsMCsW3DUbWsjgqTo5" forHTTPHeaderField:@"X-KaChing-APIKey"];	
	
	//Set the request method to PUT
	[request setHTTPMethod:@"DELETE"];
	
	// Perform request
	[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
}

//This method performs an HTTP POST method to trade a stock
-(void) trade:(NSString *) symbol By:(NSString *) action And:(NSString *) type For:(NSString *) quantity If:(NSString *) limit By:(NSString *) endOfDay
{
	//create a string to be used as the request's URL
	NSString* fullURL = [NSString stringWithFormat:@"http://www.kaching.com/api/users/%@/portfolio/orders", userID];
	
	// Prepare URL request with the above URL
	NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:fullURL]];
	
	//change the content length header to 0 since we are not sending or receiving any data in the body.
	//[request addValue:@"0" forHTTPHeaderField:@"Content-Length"];
	
	/**************add trade information to the POST body************/
	//Create the BodyString and convert it into NSData
	NSString *bodyString;
	if(limit == @"" && endOfDay == @"")
	{
		bodyString = [NSString stringWithFormat:@"type=%@&action=%@&symbol=%@&quantity=%@", type, action, symbol, quantity];
	}
	else{
		NSLog(@"limit = %@", limit);
		bodyString = [NSString stringWithFormat:@"type=%@&action=%@&symbol=%@&quantity=%@&limit=%@&endOfDay=%@", type, action, symbol, quantity, limit, endOfDay];
	}
	NSData *bodyData = [bodyString dataUsingEncoding:NSASCIIStringEncoding];
	
	//Debug
	NSLog(bodyString);
	
	//add the data to the HTTPBody
	[request setHTTPBody:bodyData];
	/**************************************************************/
	
	
	//add the remote key as a header
	[request addValue:remoteKey forHTTPHeaderField:@"X-KaChing-RemoteKey"];
	
	//add the API key (J-BJc1KZEiTQdphsMCsW3DUbWsjgqTo5) as a header
	[request addValue:@"J-BJc1KZEiTQdphsMCsW3DUbWsjgqTo5" forHTTPHeaderField:@"X-KaChing-APIKey"];	
	
	
	//Set the request method to PUT
	[request setHTTPMethod:@"POST"];
	
	//debug
	NSLog([request description]);
	
	// Perform request
	[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
}

- (void)dealloc {
	[parser release];
	[remoteKey release];
    [connection cancel];
    [connection release];
    [data release];
	[imageView release];
	[caller release];
    [super dealloc];
}

@end
